const fs = require('fs');
const express = require('express');
const app = express();

app.use(express.urlencoded());
app.use('/', express.static('./public'));

//get-查  读取pets.json文件数据进行展示
app.get('/api/v1/pets', (req, res) => {
    const pets = JSON.parse(fs.readFileSync('./db/pets.json').toString());
    res.json(pets);
});

// post-增 存储顾客的数据放在pets.json文件里
app.post('/api/v1/pets', (req, res) => {
    const pets = JSON.parse(fs.readFileSync('./db/pets.json').toString());
    pets.push({
        id: Date.now(),
        ...req.body
    });
    fs.writeFileSync('./db/pets.json', JSON.stringify(pets));
    res.json({
        code: 1,
        msg: '保存数据成功',
    });
});

// delete-删 
app.delete('/api/v1/pets/:id', (req, res) => {
    const {
        id
    } = req.params;
    const pets = JSON.parse(fs.readFileSync('./db/pets.json').toString());
    const index = pets.findIndex(item => item.id == id);
    pets.splice(index, 1);
    fs.writeFileSync('./db/pets.json', JSON.stringify(pets));
    res.json({
        code: 1,
        msg: '删除成功',
    });
});

// put-修改
app.put('/api/v1/pets/:id', (req, res) => {
    const {
        id
    } = req.params;
    const pets = JSON.parse(fs.readFileSync('./db/pets.json').toString());
    const index = pets.findIndex(item => item.id == id);
    pets[index] = {
        ...{
            id
        },
        ...req.body
    };
    fs.writeFileSync('./db/pets.json', JSON.stringify(pets));
    res.json({
        code: 1,
        msg: '修改成功',
    });
});

// 端口号
app.listen(3334, () => {
    console.log('服务器运行在3334端口');
})